package com.atmc.service.impl;

import com.atmc.entity.Authority;
import com.atmc.entity.LoginUser;
import com.atmc.entity.User;
import com.atmc.mapper.UserMapper;
import com.atmc.service.AuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    AuthorityService authorityService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        User user = userMapper.selectOne(username);
        Long user_id = user.getUserId();
        //如果查询不到数据就通过抛出异常来给出提示
        if(ObjectUtils.isEmpty(user)){
            throw new RuntimeException("用户密码错误！");
        }
        //TODO 根据用户查询权限信息 添加到LoginUser中
//        List<String> list=new ArrayList<>(Arrays.asList("hello","demo"));
        List<String> list=new ArrayList<>();
        List<String> lists=new ArrayList<>();
        List<Authority> authorities = authorityService.selectAuthority(user_id);
        for (Authority authority : authorities) {
            lists.add(authority.getAuthorName());
        }
        //封装成UserDetails对象返回
        return new LoginUser(user,lists);
    }
}